package com.example.demo.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWTUtils {
    private static String SIGNATURE = "token!@#$%^7890";

    /**
     * 生成token
     * @param  id
     * @return 返回token
     */
    public static String getToken(int id){
        Map<String,Object> map = new HashMap<>();
        map.put("id",id+"");
        JWTCreator.Builder builder = JWT.create();
        map.forEach((k,v)->{
            builder.withClaim(k, (String) v);
        });
        //        .setExpiration()//过期时间
        //        7天有效
        builder.withExpiresAt(new Date(System.currentTimeMillis() + 60*60*1000*24*7));
        return builder.sign(Algorithm.HMAC256(SIGNATURE)).toString();
    }



    /**
     * 根据token获取用户id
     * @param token
     * @return id
     */
    public static int getIdByToken(String token){
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);
        return Integer.parseInt(decodedJWT.getClaim("id").asString());
    }

}